<template>
  <div>
    <transition enter-active-class="animated fadeInDown" leave-active-class="animated fadeOutUp">
      <div class="modal" v-show="show" style="display:block" @click.self="close">
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <button @click="close" class="close">×</button>
              <h4 class="modal-title">
                <slot name="title"></slot>
              </h4>
            </div>
            <div class="modal-body">
              <slot></slot>
            </div>
            <div class="modal-footer">
              <slot name="footer"></slot>
            </div>
          </div>
        </div>
      </div>
    </transition>

    <transition name="fade">
      <div v-show="show" class="modal-backdrop fade in" @click="close"></div>
    </transition>
  </div>
</template>

<script>
export default {
  name: "Modal",
  props: {
    show: {
      type: Boolean,
      default: false
    }
  },

  methods: {
    // 触发父组件关闭本弹窗
    close() {
      // 触发事件以关闭弹窗
      this.$emit("update:show", false);
    }
  },

  // 监听show属性
  watch: {
    show(value) {
      // 监听show值以切换body上modal-open类
      const bodyCalssList = document.body.classList;

      if (value) {
        bodyCalssList.add("modal-open");
      } else {
        bodyCalssList.remove("modal-open");
      }
    }
  }
};
</script>

<style scoped>
.animated {
  animation-duration: 0.4s;
}
.fade-enter,
.fade-leave-to {
  opacity: 0;
}
</style>
